#include "videowidget.h"
#include "ui_videowidget.h"

VideoWidget::VideoWidget(QString path, QWidget *parent) :
    BaseWidget(parent)//,ui(new Ui::VideoWidget)
{
    //ui->setupUi(this);


    connect(&process, &QProcess::readyReadStandardOutput, this, &VideoWidget::onReadyRead);
    connect(this, &VideoWidget::finishLoad, this, [&, path]()
    {
        loading->stop(true);
        loading->deleteLater();
        isloading = false;
        update();

        if(list.size() > 0)
        {
            QString cmd = QString(PATH "mplayer -slave -quiet -input file=/tmp/myfifo -geometry 0:0 -zoom -x 1024 -y 600 %1 &").arg(path);
            qDebug() << "cmd:" << cmd;
            process.start(cmd);
        }
    });

    list.clear();
    std::thread([&]{
        QProcess p;
        QString path = QString(PATH VIDEO_PATH);
        p.start("find " + path + " -type f -iname \"*.mp4\"");
        p.waitForFinished();
        QString data = p.readAll();
        list = data.split("\n", QString::SkipEmptyParts);

        log_debug() << path << " " << list << " " << data;
        emit finishLoad();
    }).detach();

    setFocusPolicy(Qt::StrongFocus);

    system("rm /tmp/myfifo -f");
    int ret = mkfifo("/tmp/myfifo", 0777);
    if(-1 == ret)
    {
        perror("mkfifo failed");
    }

    fd = open("/tmp/myfifo", O_RDWR);
    if(-1 == fd)
    {
       perror("open fifo failed");
       return ;
    }

    connect(this, &VideoWidget::sigLongPress, this, [&]{close();});
    /*
    player = new QMediaPlayer;
    videoWidget = new QVideoWidget(this);
    videoWidget->setFixedSize(1024, 600);
    player->setVideoOutput(videoWidget);

    connect(player, SIGNAL(error(QMediaPlayer::Error)), this, SLOT(error(QMediaPlayer::Error)));
    connect(player, &QMediaPlayer::mediaStatusChanged, this, [&](QMediaPlayer::MediaStatus status)
    {
        qDebug() << "status:" << status;
    });
    player->setMedia(QUrl::fromLocalFile("./1.mp4"));
    player->play();*/
}

VideoWidget::~VideoWidget()
{
    //delete ui;
    system("killall -9 mplayer");
    process.close();
    ::close(fd);
}

void VideoWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    QBrush b(QColor("#424655"));
    //painter.setBrush(b);
    painter.fillRect(rect(), b);

}
#if 0
void VideoWidget::error(QMediaPlayer::Error err)
{
    qDebug() << "error:" << err << " " << player->errorString();
}
#endif
void VideoWidget::onReadyRead()
{
    qDebug() << "read:" << process.readAllStandardOutput();
}

void VideoWidget::slotChangeVideo(QString p)
{
    log_debug() << "play : " << p;
    space::startCmd("killall mplayer");
    QString cmd = QString(PATH "mplayer -slave -quiet -input file=/tmp/myfifo -geometry 0:0 -zoom -x 1024 -y 600 %1 &").arg(p);
    process.close();
    process.start(cmd);
}

void VideoWidget::KeyEvent(Key_t type, int key)
{
    qDebug() << "MainView:key=" << key << " type=" << type;
    if(key == 0)
    {
        sigChangeVideo(0);
#if 0
        if(list.size() <= 0)
            return ;

        if(type == KEY_PRESS)
        {
            if(index == 0)
                index = list.size()-1;
            else index--;

            playVideo();
        }
#endif
    }
    else if(key == 1)
    {
        sigChangeVideo(1);
#if 0
        if(list.size() <= 0)
            return ;

        if(type == KEY_PRESS)
        {
            index++;
            index %= list.size();

            playVideo();
        }
#endif
    }
    else if(key == 2)
    {
        if(type == KEY_PRESS)
        {
            close();
        }
    }
}

void VideoWidget::playVideo()
{
    space::startCmd("killall mplayer");
    QString cmd = QString(PATH "mplayer -slave -quiet -input file=/tmp/myfifo -geometry 0:0 -zoom -x 1024 -y 600 %1 &").arg(list.at(index));
    process.close();
    process.start(cmd);
}

void VideoWidget::mouseReleaseEvent(QMouseEvent *e)
{
    press = false;
    move = false;
    BaseWidget::mouseReleaseEvent(e);
}

void VideoWidget::mouseMoveEvent(QMouseEvent *e)
{
    if(press && !move)
    {
        if((e->pos().x() - pos.x() >= 30))
        {
            move = true;
            //last
            sigChangeVideo(0);
        }
        else if(e->pos().x() - pos.x() <= -30)
        {
            move = true;
            //next
            sigChangeVideo(1);
        }
    }

    BaseWidget::mouseMoveEvent(e);
}

void VideoWidget::mousePressEvent(QMouseEvent *e)
{
    pos = e->pos();
    press = true;
    BaseWidget::mousePressEvent(e);
}

void VideoWidget::keyPressEvent(QKeyEvent *event)
{
    qDebug() << "keyPressEvent";
    if(event->key() == Qt::Key_A)
    {
        KeyEvent(KEY_PRESS, 0);
    }
    else if(event->key() == Qt::Key_D)
    {
        KeyEvent(KEY_PRESS, 1);
    }
    else if(event->key() == Qt::Key_Escape)
    {
        KeyEvent(KEY_PRESS, 2);
    }
}


